# -*- encoding: utf-8 -*-
# @File    :   __init__.py
# @Time    :   2021/07/23 15:15:47
# @Author  :   wudongmin
# @Contact :   wudongmin@xroom.net
# @version   :  1.0
from app.model import engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.query import Query
from sqlalchemy.sql.expression import desc, asc
from app.items import PagniationItem, OrderItem, OrderMethodEnum, OrderByEnum

class RepositoryBase(object):
    """db"""

    def __init__(self) -> None:
        self._session = sessionmaker(engine)()
        super().__init__()

    def pagination(self, filter: Query, page_params: PagniationItem = None) -> Query:
        # 分页filter
        if page_params is not None:
            f = filter.offset((page_params.page-1)*page_params.per_page).limit(page_params.per_page)
            return f
        else:
            return filter

    def sort_filter(self, filter: Query, order_params: OrderItem = None) -> Query:
        # 排序filter
        if order_params is None:
            return filter.order_by(desc(OrderByEnum.CREATED_AT.value))
        else:
            if order_params.order_method.value == OrderMethodEnum.DESC.value:
                return filter.order_by(desc(order_params.order_by.value))
            elif order_params.order_method.value == OrderMethodEnum.ASC.value:
                return filter.order_by(asc(order_params.order_by.value))